import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import qs from 'qs'
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject'

const http = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  timeout: 1000 * 180,
  withCredentials: true
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  config.headers['token'] = Cookies.get('token') || ''
  // 默认参数
  var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{ '_t': new Date().getTime() }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.code === 10001) {
    clearLoginInfo()
    router.replace({ name: 'login' })
    return Promise.reject(response.data.msg)
  }
  return response
}, error => {
  console.error(error)
  return Promise.reject(error)
})

/*************axios二次封装start***************/
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export async function get(url,data){
  try {
    let res = await http.get(url, {params: data});
    res = res.data;
    return new Promise((resolve) => {
      if (res.code === 0) {
        resolve(res)
      } else {
        reject(res)
      }
    })
  } catch (err) {
    alert('服务器出错');
    console.log(err)
  }
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export async function post(url,data = {}){
  try {
    let res = await http.post(url, Qs.stringify(data, {arrayFormat: 'repeat'}))
    res = res.data;
    return new Promise((resolve, reject) => {
      if (res.code === 0) {
        resolve(res)
      } else {
        reject(res)
      }
    })
  } catch (err) {
    // return (e.message)
    alert('服务器出错');
    console.log(err)
  }
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    http.patch(url,data)
        .then(response => {
          resolve(response.data);
        },err => {
          reject(err)
        })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    http.put(url,data)
        .then(response => {
          resolve(response.data);
        },err => {
          reject(err)
        })
  })
}
/*************axios二次封装end***************/
export default http
